/**
 * Created by zy on 2016/6/8.
 * 列表 - 其他缺陷管理
 */


;(function ($, window, document, undefined) {

    // 管道
    var $pipeline = $('#JQ_pipeline').select3();
    // 管段
    var $segment = $('#JQ_segment').select3({
        title:'管段'
    });
    // 起点位置
    var $begin = $('#JQ_begin').select3({
        title: '起点位置',
        server: true,
        mileType: 'float',
        param: {'pipeLineId':$pipeline,'pipeSegmentId':$segment}
    });
    // 终点位置
    var $end = $('#JQ_end').select3({
        title:'终点位置',
        server: true,
        mileType: 'float',
        param: {'pipeLineId':$pipeline,'pipeSegmentId':$segment,'beginSignId':$begin}
    });
    // 触发管道
    $pipeline.element.on('select',function(e,v){
        var id = v || $pipeline.val();
        if(id){
            // 管段
            DyyBase.ajax(DyyBase.url_segment(), {pipeLineId:id}, function(dataset){
                var json = DyyBase.getSelect(dataset);
                $segment.add(json);
            });
            // 起点 & 终点
            DyyBase.ajax(DyyBase.url_pipe_pos(), {pipeLineId:id}, function(dataset){
                var begin = DyyBase.getPos(dataset,'begin', true);
                var end = DyyBase.getPos(dataset,'end', true);
                $begin.asset(begin);
                $end.asset(end);
            });
        }else{
            $segment.add([]);
            $begin.add([]);
            $end.add([]);
        }
    });
    // 触发管段
    $segment.element.on('select',function(e,v){
        var id = v || $segment.val();
        if(id){
            // 起点 & 终点
            DyyBase.ajax(DyyBase.url_segment_pos(), {pipeSegmentId:id}, function(dataset){
                var begin = DyyBase.getPos(dataset,'begin', true);
                var end = DyyBase.getPos(dataset,'end', true);
                $begin.asset(begin);
                $end.asset(end);
            });
        }else{
            $begin.add([]);
            $end.add([]);
        }
    });
    // 缺陷来源
    var $source = $('#JQ_source').select3({search:false});
    // 缺陷状态
    var $status = $('#JQ_status').select3({search:false}).reset();
    // 统计form
    var $statistics_form = $('#JQ_statistics_form');
    // 填充缺陷来源
    DyyBase.ajax(defectApi.url_defect_source(), {}, function (dataset) {
        var json = DyyBase.getSelect(dataset);
        $source.add(json);
    });

    // 发现日期 - 1
    var $date_01 = $('#JQ_find_date_01');
    // 发现日期 - 2
    var $date_02 = $('#JQ_find_date_02');

    // 查询对象
    var filter = {
        // 获得查询条件
        getSearch: function (param) {
            // 返回对象
            var data = {};
            // 默认为true，意为开启各项验证
            data.mode = true;
            // 分页参数
            if (param) {
                if (param.start == 0) {
                    data['jsonBean.pageNum'] = 1;
                } else {
                    data['jsonBean.pageNum'] = param.start / 10 + 1;
                }
                data['jsonBean.pageCount'] = param.length;
            }
            // 管道
            data.lineId = function () {
                var v = $pipeline.val();
                if (v) {
                    return v;
                }
                return '';
            }();
            // 起点位置
            data.begin = function () {
                var v = $begin.val('mile');
                if (v) {
                    return v;
                }
                return '';
            }();
            // 终点位置
            data.end = function () {
                var v = $end.val('mile');
                if (v) {
                    return v;
                }
                return '';
            }();
            // 缺陷来源
            data.defectSource = function () {
                var v = $source.val();
                if (v) {
                    return v;
                }
                return '';
            }();
            // 缺陷状态
            data.dataState = function () {
                var v = $status.val();
                if (v) {
                    return v;
                }
                return '';
            }();
            // 发现时间 - 开始
            data.beginTime = function () {
                var v = $date_01.val();
                if (v) {
                    return v;
                }
                return '';
            }();
            // 发现时间 - 结束
            data.endTime = function () {
                var v1 = $date_01.val();
                var v2 = $date_02.val();
                if (v2) {
                    if (v1) {
                        if (!(Dyy.checkDateLate(v1,v2))) {
                            $date_02.TIP({'content': '结束日期应当晚于开始日期!'});
                            data.mode = false;
                        }
                    }
                    return v2;
                }
                return '';
            }();
            return data;
        },
        // 获得选中项
        getSelected: function () {
            var $chks = $table_non.find('i.zy-checkbox');
            var arr = [];
            $chks.each(function () {
                var $this = $(this);
                if ($this.hasClass('active')) {
                    arr.push($this.attr('data-id'));
                }
            });
            return arr;
        },
        // 获得导出 & 统计条件
        getExport: function(){
            return filter.getSearch();
        }
    };

    // 初始化表格控件
    var $table_non = $('#JQ_table_non').checkbox3();

    // 初始加载表格
    var DTNON = $table_non.DataTable({
        'language': {
            'paginate': {
                'next': '下一页',
                'previous': '上一页'
            },
            'info': '本次检索共 _TOTAL_ 条，每页显示 10 条，共 _PAGES_ 页',
            'zeroRecords': DyyBase.defect_empty(),
            'infoEmpty': ''
        },
        'autoWidth': false,
        'order': [],
        'serverSide': true,
        'pageLength': 10,
        'ordering': false,
        'processing': false,
        'searching': false,
        'lengthChange': false,
        'ajax': function (data, callback) {
            var param = filter.getSearch(data);
            DyyBase.ajax(defectApi.url_external_list(), param, function (dataset) {
                var returnData = {};
                returnData.draw = data.draw;
                returnData.recordsTotal = dataset.result.defect.total;
                returnData.recordsFiltered = dataset.result.defect.total;
                returnData.data = DyyBase.clearNull(dataset.result.defect.list);

                // 待审核缺陷
                $('#JQ_defect_num').text(dataset.result.pendingAudit);

                // 回调渲染
                callback(returnData);
            });
        },
        'drawCallback': function () {
            $('i.zy-checkbox-all').trigger('clear');
        },
        'columns': [
            {
                data: 'id', render: function (data) {
                return '<i class="zy-checkbox" data-id="' + data + '" title="选中"></i>';
            }
            },
            {
                data: 'lineName', render: function (data) {
                return '<span title="' + data + '">' + data + '</span>';
            }
            },
            {
                data: 'featureSubtype', render: function (data) {
                return '<span title="' + data + '">' + data + '</span>';
            }
            },
            {
                data: 'mileage', render: function (data) {
                return '<span title="' + data + '">' + data + '</span>';
            }
            },
            {
                data: 'length', render: function (data, type, row) {
                return '<span title="' + data + '/' + row.width + '/' + row.depth + '">' + data + '/' + row.width + '/' + row.depth + '</span>';
            }
            },
            {
                data: 'state_lable', render: function (data) {
                return '<span title="' + data + '">' + data + '</span>';
            }
            },
            {
                data: 'clock', render: function (data) {
                return '<span title="' + data + '">' + data + '</span>';
            }
            },
            {
                data: 'source', render: function (data) {
                return '<span title="' + data + '">' + data + '</span>';
            }
            },
            {
                data: 'id', render: function (data,type,row) {
                if(row.reportPath && row.reportPath != '-'){
                    return '<i data-id="' + data + '" class="zy-upload-icon" title="上传报告"></i>&nbsp;<i data-id="' + data + '" class="zy-delete-upload-icon" title="删除报告"></i>&nbsp;<i data-id="' + data + '" data-type="defectInspectionReport" data-pipename="'+row.lineName+'" data-defect="'+row.defectType+'" class="zy-down-upload-icon" title="下载报告"></i>';
                }else{
                    return '<i data-id="' + data + '" class="zy-upload-icon" title="上传报告"></i>&nbsp;<i data-id="' + data + '" class="zy-delete-upload-icon disabled" title="没有可删除项"></i>&nbsp;<i data-id="' + data + '" class="zy-down-upload-icon disabled" title="没有可下载项"></i>';
                }
            }
            },
            {
                data: 'id', render: function (data) {
                return '<i data-id="' + data + '" class="zy-details-icon" title="展开详情"></i>';
            }
            },
            {
                data: 'state_lable', render: function (data, type, row) {
                if (data == '待审核') {
                    return '<a href="' + defectApi.url_external_audit_page() + '?id=' + row.id + '"><i data-tag="' + data + '" class="zy-shenhe-icon" title="待审核"></i></a>';
                } else {
                    return '<i data-tag="' + data + '" class="zy-shenhe-no-icon" title="不能审核"></i>';
                }
            }
            },
            {
                data: 'repairShow', render: function (data, type, row) {
                if (data == 1) {
                    return '<i data-id="' + row.id + '" data-tab="'+row.repairTab+'" data-tag="'+row.repairName+'" class="zy-record-icon" title="查看记录"></i>';
                } else if (data == 2) {
                    return '<i data-id="' + row.id + '" class="zy-record-no-icon" title="不可操作"></i>';
                } else if (data == 3) {
                    if(row.repairTab){
                        var url = DyyBase.root_path+'/pbf/externalRepair/'+row.repairTab+'Init.html?defectId='+row.id;
                        return '<a href="'+url+'"><i data-id="' + row.id + '" class="zy-record-add-icon" title="添加记录"></i></a>';
                    }
                    return '<i data-id="' + row.id + '" class="zy-record-add-icon" title="添加记录"></i>';
                }
            }
            }
        ]
    });

    // 重绘表格
    function draw(){
        if(DTNON){
            DTNON.draw();
        }
    }


    /*** 详情 - start ***/
    // 展开
    $table_non.on('click', 'i.zy-details-icon', function (event) {
        // 当前对象
        var $this = $(this);
        // 获取携带id
        var id = $this.attr('data-id');
        // 父级tbody
        var $tbody = $this.parent('td').parent('tr').parent('tbody');
        // 父级tr
        var $ptr = $this.parent('td').parent('tr');
        // 查找存在tr
        var $exist_tr = $tbody.find('tr[data-details="' + id + '"]');
        // 隐藏其他添加tr
        $table_non.find('tr.zy-dy-tr').hide();
        $table_non.find('i').removeClass('active');
        // 激活当前按钮
        $this.addClass('active');
        if ($exist_tr.length > 0) {
            $exist_tr.show();
        } else {
            fillDetails($this,$ptr,DTNON.row($ptr).data());
        }
        event.stopPropagation();
    });

    // 填充
    function fillDetails(ibtn,ptr,data) {
        var $dy_tr = $('<tr class="zy-dy-tr" data-details="' + data.id + '"><td colspan="12"><div class="zy-details-box"></div></td></tr>');
        var $div = $dy_tr.find('div.zy-details-box');
        var img_id = 'img' + data.id;

        var content = '<div class="zy-dy-inner">';
        content += '<div class="zy-dy-head">';
        content += '<p><span>管道名称：</span><span title="'+data.lineName+'">' + data.lineName + '</span></p>';
        content += '<p><span>缺陷编号：</span><span title="'+data.customNumber+'">' + data.customNumber + '</span></p>';
        content += '<p><span>缺陷类型：</span><span title="'+data.featureSubtype+'">' + data.featureSubtype + '</span></p>';
        content += '<p><span>缺陷来源：</span><span title="'+data.source+'">' + data.source + '</span></p>';
        /*content += '<p><span>绝对距离(m)：</span><span title="'+data.mileage+'">' + data.mileage + '</span></p>';*/
        content += '<p><span>缺陷状态：</span><span title="'+data.state_lable+'">' + data.state_lable + '</span></p>';
        content += '<p><span>发现时间：</span><span title="'+data.foundTimeStr+'">' + data.foundTimeStr + '</span></p>';
        content += '<p><span>维修记录：</span><span title="'+data.repairState_lable+'">' + data.repairState_lable + '</span></p>';
        content += '<div class="zy-details-mark"><span title="'+data.createRemark+'">备注：</span><span>' + data.createRemark + '</span></div>';
        if(data.remark != '-'){
            content += '<div class="zy-details-mark"><span title="'+data.remark+'">不通过原因：</span><span>' + data.remark + '</span></div>';
        }
        content += '</div>';

        content += '<div class="zy-dy-body">';
        content += '<p>' +
            '<dfn class="zy-dy-label-title"><i class="zy-dy-pos-icon"></i><span><cite class="f16">位置信息</cite><br><abbr class="f12 c-90">Position information</abbr></span></dfn>' +
            '<label class="w-15"><em title="'+data.mileage+'" class="f16">' + data.mileage + '</em><br><em class="c-90 f12">绝对距离(m)</em></label>' +
            '<label class="w-15"><em title="'+data.reference+'" class="f16">' + data.reference + '</em><br><em class="c-90 f12">最近参考点</em></label>' +
            '<label class="w-15"><em title="'+data.referenceDistance+'" class="f16">' + data.referenceDistance + '</em><br><em class="c-90 f12">距参考点(m)</em></label>' +
            '<label class="w-15"><em title="'+data.ugwNumber+'" class="f16">' + data.ugwNumber + '</em><br><em class="c-90 f12">上游环焊缝编号</em></label>' +
            '<label class="w-15 zy-no-bg"><em title="'+data.distancetougwNumber+'" class="f16">' + data.distancetougwNumber + '</em><br><em class="c-90 f12">相对上游环焊缝距离(m)</em></label>' +
            '</p>';
        content += '<p>' +
            '<dfn class="zy-dy-label-title"><i class="zy-dy-defact-icon"></i><span><cite class="f16">缺陷信息</cite><br><abbr class="f12 c-90">Defact information</abbr></span></dfn>' +
            '<label class="w-15"><em title="'+data.maxDepth+'" class="f16">' + data.maxDepth + '</em><br><em class="c-90 f12">峰值深度(%)</em></label>' +
            '<label class="w-15"><em title="'+data.length+'/'+data.width+'/'+data.depth+'" class="f16">' + data.length + '/' + data.width + '/' + data.depth + '</em><br><em class="c-90 f12">长/宽/深(mm)</em></label>' +
            '<label class="w-15"><em title="'+data.x+'•'+data.y+'•' +data.z+'" class="f16">' + data.x + '•' + data.y + '•' + data.z + '</em><br><em class="c-90 f12">缺陷坐标(x.y.z)</em></label>' +
            '<label class="w-15"><em title="'+data.clock+'" class="f16">' + data.clock + '</em><br><em class="c-90 f12">时钟方位(时:分)</em></label>' +
            '<label class="w-13 zy-no-bg"><em title="'+data.buriedDepth+'" class="f16">' + data.buriedDepth + '</em><br><em class="c-90 f12">埋深数据(m)</em></label>' +
            '</p>';
        content += '<p>' +
            '<dfn class="zy-dy-label-title"><i class="zy-dy-photo-icon"></i><span><cite class="f16">照片</cite><br><abbr class="f12 c-90">Photo information</abbr></span></dfn>' +
            '<abbr class="zy-details-img-box w-50" data-id="'+ data.id +'"></abbr>' +
            '</p>';
        content += '</div>';
        content += '<div class="zy-dy-footer"><button type="button" class="zy-button zy-pick-up" data-id=""><i></i>收起</button></div>';
        content += '</div>';
        $div.html(content);

        // 获取图片
        DyyBase.ajax(defectApi.url_external_img(),{id:data.id},function(dataset){
            if(dataset.bool){
                var str = '';
                var imgs = [];

                /*if(dataset.result.image){
                    for(var i = 0, len = dataset.result.image.length; i < len; i++){
                        str += '<img src="'+DyyBase.file_path+dataset.result.image[i].path+'">';
                        imgs.push(DyyBase.file_path+dataset.result.image[i].path);
                    }
                }
                 $('abbr.zy-details-img-box').empty().html(str);
                 $('abbr.zy-details-img-box').loadSmallImage(imgs);
                */

                //xyf edit 2012-12-22
                if(dataset.result.image.length>0){
                    imgs = DyyBase.getImagePath(dataset.result.image);
                }

                var $abbrImg = $('abbr.zy-details-img-box');
                for(var j=0;j<$abbrImg.length;j++){
                    var $curAbbr = $abbrImg[j];
                    var data_id = $($curAbbr).attr('data-id');
                    if(data_id == data.id){
                        $($curAbbr).empty().html(str);
                        $($curAbbr).loadSmallImage(imgs);
                    }
                }

            }
        });

        // 收起按钮
        var $pull = $div.find('button.zy-button');
        $pull.click(function () {
            ibtn.removeClass('active');
            $dy_tr.hide();
        });

        // 添加
        ptr.after($dy_tr);
    }
    /*** 详情 - end ***/


    /*** 维修记录 - start ***/
    // 展开
    $table_non.on('click', 'i.zy-record-icon', function (event) {
        var $this = $(this);
        var id = $this.attr('data-id');
        var tab = $this.attr('data-tab');
        var tag = $this.attr('data-tag');

        var $ptr = $this.parent('td').parent('tr');
        var $tbody = $this.parent('td').parent('tr').parent('tbody');
        var $exist_tr = $tbody.find('tr[data-record="' + id + '"]');

        $table_non.find('tr.zy-dy-tr').hide();
        $table_non.find('i').removeClass('active');
        $this.addClass('active');

        if ($exist_tr.length > 0) {
            $exist_tr.show();
        } else {
            fillRecord($this,$ptr,id,tab,tag);
        }
        event.stopPropagation();
    });

    // 换管信息切换
    $table_non.on('click', 'i.zy-num-click', function(){
        var $this = $(this);
        $table_non.find('i.zy-num-click').removeClass('active');
        $this.addClass('active');
        var tab = $this.attr('data-tab');
        $table_non.find('div.zy-repair-info-body').empty().append(pipe_replace[tab]);
    });

    // 填充
    function fillRecord(ibtn,ptr,id,tab,tag) {
        var $dy_tr = $('<tr class="zy-dy-tr" data-record="' + id + '"><td colspan="12"><div class="zy-details-box"></div></td></tr>');
        var $div = $dy_tr.find('div.zy-details-box');

        var url = DyyBase.root_path+'/pbf/externalRepair/'+tab+'Show.json?defectId='+id;
        DyyBase.ajax(url,{},function(dataset){
            // 模板内容
            var content = '';
            // 容器
            var $box = $('<div class="zy-repair-info-box"></div>');
            // 头 - 身 - 脚
            var head = '', $body = $('<div class="zy-repair-info-body"></div>'), $footer = $('<div class="zy-dy-footer"></div>');
            // 收起按钮
            var $pick_btn = $('<button type="button" class="zy-button zy-pick-up" data-id=""><i></i>收起</button>');
            $pick_btn.click(function(){
                ibtn.removeClass('active');
                $table_non.find('tr[data-record="'+id+'"]').hide();
            });

            if(tab == 'repairReplacePipe'){
                content = Template.getTemplate2(dataset.result);
                head = '<div class="zy-dy-status"><p><span><i class="zy-num-click" data-tab="repairReplacePipe">1</i>换管</span></p><p class="zy-dy-bg"></p><p><span><i class="zy-num-click" data-tab="repairPipeWelding">2</i>焊接</span></p></div>';
            }else{
                content = Template.getTemplate(dataset.result);
                head = '<div class="zy-dy-status"><p><span><i>1</i>'+tag+'</span></p></div>';
            }

            $body.append(content);
            $footer.append($pick_btn);
            $box.append(head).append($body).append($footer);
            $div.empty().append($box);
            ptr.after($dy_tr);
        });
    }
    /*** 维修记录 - end ***/


    // 删除报告
    $table_non.on('click', 'i.zy-delete-upload-icon', function(event){
        var $this = $(this);
        var id = $this.attr('data-id');
        if(id && !($this.hasClass('disabled'))){
            $this.MSG({
                type: 'confirm',
                tag: 'no',
                height: 230,
                content: '确认要删除缺陷报告?',
                yesBtnTxt: '确认',
                yesBtnAct: function(){
                    DyyBase.ajax(defectApi.url_external_delete_file(),{businessId:id},function(dataset){
                        if(dataset.bool){
                            $this.MSG({
                                type: 'success',
                                content: '删除缺陷报告成功!',
                                yesBtnAct: draw,
                                closeBtnAct: draw
                            });
                        }else{
                            $this.MSG({
                                type: 'error',
                                content: dataset.result
                            });
                        }
                    })
                }
            });
        }
        event.stopPropagation();
    });

    // 上传报告
    $table_non.on('click', 'i.zy-upload-icon', function (event) {
        var $this = $(this);
        var id = $this.attr('data-id');
        $this.UPW({
            businessId: id,
            closeBtnAct: function(callback){
                callback();
                draw();
                //console.log($this.data('info'));
            }
        });
        event.stopPropagation();
    });

    // 下载报告
    $table_non.on('click', 'i.zy-down-upload-icon', function(event){
        var $this = $(this);
        var $form = $('#JQ_download_form').empty();
        var $iframe = $('#JQ_download_iframe').empty();
        var postObj = {
            businessId: $this.attr('data-id'),
            downFileName: $this.attr('data-pipename') + $this.attr('data-defect') + '缺陷检测报告',
            type: 'defectInspectionReport'
        };
        for(var k in postObj){
            var $input = $('<input type="hidden">');
            $input.prop('name', k).val(postObj[k]);
            $form.append($input);
        }
        $form.submit();
        $iframe.get(0).onload = function(){
            try{
                var content = this.contentWindow.document.body.innerHTML;
                content = $.parseJSON(content);
                if(content.bool){

                }else{
                    $this.MSG({
                        type: 'error',
                        content: content.result
                    });
                }
            }catch(e){
                $this.MSG({
                    type: 'error',
                    content: e.message
                });
            }
        }
    });

    // 搜索
    $('#JQ_search_btn').click(function () {
        var param = filter.getSearch();
        if(param.mode){
            if(DTNON){
                DTNON.draw();
                filter.getExport = param;
            }
        }
    });

    // 导出
    $('#JQ_export_btn').click(function () {
        $(this).EXPT({
            name: '非内检测缺陷信息表',
            param: filter.getExport,
            server: DyyBase.root_path + '/pbf/external/queryDataExl.json'
        });
    });

    // 删除
    $('#JQ_delete_btn').click(function () {
        var $this = $(this);
        var param = filter.getSelected();
        var len = param.length;
        if(len){
            var ids = [];
            for(var i = 0; i < len; i++){
                ids.push({name:'ids',value:param[i]});
            }
            $this.MSG({
                type: 'confirm',
                tag: 'no',
                yesBtnTxt: '确定',
                height: 230,
                content: '请确认是否删除该缺陷点?',
                yesBtnAct: function(){
                    DyyBase.ajax(defectApi.url_external_delete(), ids, function (dataset) {
                        if (dataset.bool) {
                            if(dataset.message == 'success'){
                                $(this).MSG({
                                    type: 'success',
                                    content: '成功删除!',
                                    yesBtnAct: draw,
                                    closeBtnAct: draw
                                });
                            }else if(dataset.message == 'partSuccess'){
                                $(this).MSG({
                                    type: 'success',
                                    content: '已发布的缺陷点不可删除，其他缺陷点已成功删除!',
                                    yesBtnAct: draw,
                                    closeBtnAct: draw
                                });
                            }
                        } else {
                            $(this).MSG({
                                type: 'error',
                                content: '删除失败，已发布的缺陷点不可删除!'
                            });
                        }
                    });
                }
            });
        }else{
            $this.MSG({
                content: '请选择要删除的缺陷数据！'
            });
        }
    });

    // 统计
    $('#JQ_statistics_btn').click(function () {
        $statistics_form.empty();
        var param = filter.getExport;
        if(param instanceof Function){
            param = param();
        }
        for(var k in param){
            var $input = $('<input type="hidden">');
            $input.prop('name', k).val(param[k]);
            $statistics_form.append($input);
        }
        $statistics_form.submit();
    });


})(jQuery, window, document);